package com.xbn.xbnmall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.xbn.common.to.es.SkuEsModel;
import com.xbn.xbnmall.search.config.ElasticConfig;
import com.xbn.xbnmall.search.constant.EsConstant;
import com.xbn.xbnmall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author XBN
 * @date 2020/7/29 19:43
 * @email 78742541@qq.com
 */
@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {
    @Autowired
    RestHighLevelClient restHighLevelClient;
    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
         //将数据保存到es
        BulkRequest bulkRequest = new BulkRequest();
        //遍历数据，每个数据都是一个indexRequest，将这些索引操作放到批量请求bulkRequest中
        for (SkuEsModel model:skuEsModels
             ) {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(model.getSkuId().toString());
            String s = JSON.toJSONString(model);
            indexRequest.source(s, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, ElasticConfig.COMMON_OPITIONS);
        //判断数据添加操作是否有错误
        //TODO 批量数据操作发生错误处理
        boolean b = bulk.hasFailures();
        List<String> collect = Arrays.stream(bulk.getItems()).map(item -> {
            return item.getId();
        }).collect(Collectors.toList());
        log.info("商品上架完成:{}",collect,bulk
        .toString());
        return !b;
    }
}
